//
//  ChecklistItem.swift
//  todoList
//
//  Created by AINI on 2019/2/13.
//  Copyright © 2019 AINI. All rights reserved.
//

import Foundation
import UserNotifications
//index of 要继承objcf的方法
class ChecklistItem: NSObject,NSCoding  {
    var text = ""
    var checked = false
    var dueDate = Date()
    var shouldRemind = false
    var itemID: Int
    func toggleChecked() {
        checked = !checked
    }
    required init?(coder aDecoder: NSCoder) {
        text = aDecoder.decodeObject(forKey: "Text") as! String
        checked = aDecoder.decodeBool(forKey: "Checked")
        dueDate = aDecoder.decodeObject(forKey: "DueDate") as! Date
        shouldRemind = aDecoder.decodeBool(forKey: "ShouldRemind")
        itemID = aDecoder.decodeInteger(forKey: "ItemID")
        super.init()
    }
    override init() {
        itemID = DataModel.nextChecklistItemID()
        super.init()
    }
    func scheduleNotification() {
        if shouldRemind && dueDate > Date() {
            //1
            let content = UNMutableNotificationContent()
            content.title = "Reminder"
            content.body = text
            content.sound = UNNotificationSound.default
            //2
            let calender = Calendar(identifier: .gregorian)
            let components = calender.dateComponents([.month,.day,.hour,.minute], from: dueDate)
            //3
            let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)
            //4
            let request = UNNotificationRequest(identifier: "\(itemID)", content: content, trigger: trigger)
            //5
            let center = UNUserNotificationCenter.current()
            center.add(request)
            
            print("We should schedule a notification")
        }
    }
//    遵守了他的协议,执行协议中的方法
    func encode(with aCoder: NSCoder) {
        aCoder.encode(text, forKey: "Text")
        aCoder.encode(checked, forKey: "Checked")
        aCoder.encode(itemID, forKey: "ItemID")
        aCoder.encode(shouldRemind, forKey: "ShouldRemind")
        aCoder.encode(dueDate, forKey: "DueDate")
    }
}
